//
//  BDSetViewController.m
//  BadBoy
//
//  Created by wen on 2016/12/23.
//  Copyright © 2016年 niusaibing. All rights reserved.
//

#import "BDSetViewController.h"
#import "BDAddressViewController.h"
#import "CameraPhotoBehavior.h"
#import "BDUserModel.h"
#import "BDSettingTableViewCell.h"
#import "DatePickbehavior.h"
#import "BDFeedbackViewController.h"
#import "BDTextFieldAlert.h"
#import "BDForgetPasswordViewController.h"
#import "UMSocialCore/UMSocialCore.h"
#import "SDImageCache.h"
#import "BDFMDBTool.h"
#import "BDApplyFriendsModel.h"

@interface BDSetViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) UIView *blakeView;            //遮盖视图
@property(nonatomic,strong) NSString *timeString;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"设置");
    
    [self requestDatasource];
    [self.tableview reloadData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)requestDatasource{
    
    BDUserModel *user = [BDUserModel getCurrentUser];
    
    self.datasource = @[@[@{@"title":ASLocalizedString(@"头像"), @"image":[user.cover isNotEmpty] ? user.cover : @"avatar"},
                          @{@"title":ASLocalizedString(@"昵称"), @"subTitle":[user.nickname isNotEmpty] ? user.nickname:@""},
                          @{@"title":ASLocalizedString(@"性别"), @"subTitle":user.sex==1?ASLocalizedString(@"男"):ASLocalizedString(@"女")},
                          @{@"title":ASLocalizedString(@"生日"), @"subTitle":[user.birthday isNotEmpty] ? user.birthday:@""},
                          ],//@{@"title":ASLocalizedString(@"城市"), @"subTitle":[user.city isNotEmpty] ?user.city:@""},
                        @[@{@"title":ASLocalizedString(@"修改密码"), @"subTitle":@""},
                          @{@"title":ASLocalizedString(@"支付密码"),@"subTitle":@""},
                          @{@"title":ASLocalizedString(@"微信"), @"subTitle":user.third_party == YES ? ASLocalizedString(@"修改绑定"): ASLocalizedString(@"未绑定")},
                          @{@"title":ASLocalizedString(@"我的收货地址"), @"subTitle":@""}],
                        @[//@{@"title":ASLocalizedString(@"版本更新"), @"subTitle":@""},
                          @{@"title":ASLocalizedString(@"清除缓存"), @"subTitle":@""},
                          @{@"title":ASLocalizedString(@"意见反馈"), @"subTitle":@""}]].mutableCopy;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"setCell" forIndexPath:indexPath];
    [cell configeWithDic:self.datasource[indexPath.section][indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 80;
    }else{
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"setHeader"];
    if (header == nil) {
        header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 10)];
        header.backgroundColor = [UIColor clearColor];
    }
    return header;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger sec = indexPath.section;
    NSInteger row = indexPath.row;
    if (sec == 0) {
        if (row == 0) {
            [[CameraPhotoBehavior behavior] getPhotoWithtargetVC:self FinishBlock:^(UIImage *image) {
                [self updateUserDateWithPara:image];
            }];
        }else if (row == 1) {
            [BDTextFieldAlert showWithTitle:ASLocalizedString(@"修改昵称")placeHolder:ASLocalizedString(@"输入新昵称")finishBlock:^(NSString *text) {
                NSDictionary *para = @{@"nickname":text};
                [self updateUserDateWithPara:para];
            }];
            
        }else if (row == 2) {
            UIView *cutomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 270, 180)];
            cutomView.backgroundColor= [UIColor whiteColor];
            cutomView.layer.masksToBounds = YES;
            cutomView.layer.cornerRadius = 4;
            
            UIView *bkView = [[UIView alloc] initWithFrame:self.view.bounds];
            cutomView.center = bkView.center;
            [bkView addSubview:cutomView];
            cutomView.alpha = 0;
            bkView.backgroundColor = [UIColor clearColor];
            [[UIApplication sharedApplication].keyWindow addSubview:bkView];
            
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 270, 40)];
            titleLabel.text = ASLocalizedString(@"选择性别");
            titleLabel.font = [UIFont systemFontOfSize:17];
            titleLabel.textColor = [UIColor colorWithHexString:@"#4d7aad"];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            [cutomView addSubview:titleLabel];
            
            UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [closeButton setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
            closeButton.size = CGSizeMake(15, 15);
            closeButton.right = cutomView.width - 10;
            closeButton.centerY = titleLabel.centerY;
            [cutomView addSubview:closeButton];
            
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 270, 1)];
            line.top = titleLabel.bottom;
            line.backgroundColor = kBDColorGray;
            [cutomView addSubview:line];
            
            NSArray *buttonArr = @[ASLocalizedString(@"男"),ASLocalizedString(@"女")];
            CGFloat buttonWidth = cutomView.width - 30;
            CGFloat buttonHeight = 45;
            CGFloat sideSpace = 20;
            CGFloat space = cutomView.height - line.bottom - sideSpace * 2 - buttonHeight * 2;
            for (int i = 0; i < 2; i++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(15, line.bottom + sideSpace + (buttonHeight + space) * i, buttonWidth, buttonHeight);
                [button setTitle:buttonArr[i] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:14];
                button.tag = 123 + i;
                [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    NSInteger sex = i == 0 ? 1 : 2;
                    
                    [UIView animateWithDuration:0.3 animations:^{
                        bkView.backgroundColor = [UIColor clearColor];
                        cutomView.alpha = 0;
                    } completion:^(BOOL finished) {
                        [bkView removeFromSuperview];
                        [self updateUserDateWithPara:@{@"sex":@(sex)}];
                    }];
                }];
                button.layer.borderWidth = 1;
                button.layer.borderColor =kBDColorGray.CGColor;
                [cutomView addSubview:button];
            }
            
            [UIView animateWithDuration:0.3 animations:^{
                bkView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
                cutomView.alpha = 1;
            } completion:^(BOOL finished) {
            }];
            
            [[closeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                [UIView animateWithDuration:0.3 animations:^{
                    bkView.backgroundColor = [UIColor clearColor];
                    cutomView.alpha = 0;
                } completion:^(BOOL finished) {
                    [bkView removeFromSuperview];
                }];
            }];
        }else if (row == 3) {
            //修改生日
            BDUserModel *user = [BDUserModel getCurrentUser];
            [DatePickbehavior getDateBehaviorByCurrentDate:user.birthday startDate:nil endDate:datePickNow finishBlock:^(NSString *finialDate) {
                [self updateUserDateWithPara:@{@"birthday":finialDate}];
            }];
        }else if (row == 4) {
            //修改城市
        }
    }else if (sec == 1) {
        if (row == 0) {
            //修改密码
            BDForgetPasswordViewController *forgetVC = [[BDForgetPasswordViewController alloc] init];
            forgetVC.type = ASLocalizedString(@"修改密码");
            [self.navigationController pushViewController:forgetVC animated:YES];
        }else if (row == 1){
            BDForgetPasswordViewController *forgetVC = [[BDForgetPasswordViewController alloc] init];
            forgetVC.type = ASLocalizedString(@"支付密码");
            [self.navigationController pushViewController:forgetVC animated:YES];
        }else if (row == 2) {
            //绑定微信
            [self bindWeChat];
        }else if (row == 3) {
            //进入收货地址
            BDAddressViewController *addressVC = [[BDAddressViewController alloc]init];
            [self.navigationController pushViewController:addressVC animated:YES];
        }
    }else {
//        if (row == 0) {
//            //版本更新
//        }else
            if (row == 0) {
            //清除缓存
//                NSString *CacheString = [NSString stringWithFormat:@"%.2fM",[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0];
                [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                    
                }];
//                [[SDImageCache sharedImageCache] clearDisk];
                /**清除缓存*/
                
                NSFileManager *mgr = [NSFileManager defaultManager];
                
                NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                [mgr removeItemAtPath:cachePath error:nil];
                
                [MBManager showBriefAlert:ASLocalizedString(@"清理成功")clickHidden:NO clickBlock:nil];
                
        }else if (row == 1) {
            //意见反馈
            BDFeedbackViewController *feedVC = [[BDFeedbackViewController alloc] init];
            [self.navigationController pushViewController:feedVC animated:YES];
        }
    }
}

- (void)bindWeChat{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                // BDLog(ASLocalizedString(@"错误"));
            }else{
                UMSocialUserInfoResponse *resp = result;
                
                NSDictionary *dic = @{@"open_id":resp.openid,
                                      @"access_token":resp.accessToken};
                //开始修改信息
                [self updateUserDateWithPara:dic];
            }
        });
    }];
}

#pragma mark -----------------------修改用户信息-------------------------------
- (void)updateUserDateWithPara:(id)para{
    NSString *headerValid = [BDUserModel getHeaderValidation];
    NSString *url = [NSString stringWithFormat:@"%@user", KBDBaseURL];
    
    [MBManager showLoadingAlert:ASLocalizedString(@"更新中")clickHidden:NO clickBlock:nil];
    if ([para isKindOfClass:[UIImage class]]) {
        UIImage *image = para;
        NSString *name = @"cover";
        RACCommand *command = [BDNetworkingServer yy_POST:url parameters:nil validation:headerValid name:name dataArray:@[UIImageJPEGRepresentation(image, 1)] automaticProcessingError:YES];
        RACSignal *signal = [command execute:nil];
        
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            BDUserModel *oldUser = [BDUserModel getCurrentUser];
            [[SDImageCache sharedImageCache] removeImageForKey:oldUser.cover withCompletion:nil];
            BDUserModel *user = [BDUserModel mj_objectWithKeyValues:x];
            [user saveCurrentUser];
            [self requestDatasource];
            [self.tableview reloadData];
        }];
        
    }else{
        RACCommand *commond = [BDNetworkingServer yy_POST:url parameters:para validation:headerValid automaticProcessingError:YES];
        RACSignal *signal = [commond execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            BDUserModel *user = [BDUserModel mj_objectWithKeyValues:x];
            [user saveCurrentUser];
            [self requestDatasource];
            [self.tableview reloadData];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            NSString *alert = ASLocalizedString(@"修改失败，请稍后再试");
            if (error.code == 10004) {
                alert = ASLocalizedString(@"昵称已存在，请更换昵称");
            }
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
        }];
    }
}

- (UITableView *)tableview{
    if (!_tableview) {
        self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.tableFooterView =  [self customTableFooterView];
        _tableview.backgroundColor =[UIColor clearColor];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableview registerClass:[BDSettingTableViewCell class] forCellReuseIdentifier:@"setCell"];
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

- (UIView *)customTableFooterView{
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 10, kBDScreenWidth, 64)];
    footer.backgroundColor = [UIColor clearColor];
    
    UIButton *footerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    footerButton.size = CGSizeMake(kBDScreenWidth, 44);
    footerButton.top = 20;
    footerButton.left = 0;
    footerButton.backgroundColor = [UIColor whiteColor];
    [footerButton setTitle:ASLocalizedString(@"退出登录")forState:UIControlStateNormal];
    [footerButton setTitleColor:[UIColor colorWithHexString:@"4c4c4c"] forState:UIControlStateNormal];
    footerButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [footer addSubview:footerButton];
    
    [[footerButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.view alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"确定要退出当前账号？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"确定")] clickBlock:^(NSInteger index) {
            if (index == 1) {
                // BDLog(ASLocalizedString(@"点了确定退出"));
                
                [BDUserModel loginOut];
                
            }
        }];
    }];
    return footer;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
